import {FC, useEffect, useState} from 'react'
import {Layout, Input, Button, Collapse, Table, Modal, notification, Dropdown, ConfigProvider, Popconfirm} from "antd";
import {PlusCircleOutlined, SearchOutlined ,BarsOutlined} from "@ant-design/icons";
import type { MenuProps } from 'antd';
import validator from 'validator';
import './index.scss'
const {Header,  Content} = Layout;
import {FormGroup, FormGroupSchema} from "pb/proto/form/getFormList_pb";
import moment from "moment";
import {formApi} from "../../hooks/form/api";
import { create } from '@bufbuild/protobuf';

const FormGroupComponent: FC = () => {
    const base_form_default:FormGroup = create(FormGroupSchema , { name: '', id: '' })
    // 正确初始化状态 (使用泛型指定类型)
    const [formGroups, setFormGroups] = useState<FormGroup[]>();
    const [searchValue, setSearchValue] = useState('');
    const [activeKeys, setActiveKeys] = useState<string[]>([]);
    const [isOpen , setIsOpen] = useState<boolean>(false);
    const [api, contextHolder] = notification.useNotification();
    const [groupForm , setGroupForm] = useState<FormGroup>(base_form_default)
    const [groupModelTitle, setGroupModelTitle] =  useState<string>('新增分组');
    const [notificationQueue, setNotificationQueue] = useState<{
        type: 'success' | 'error' | 'info' | 'warning';
        message: string;
    } | null>(null);
    const from_columns = [
        {
            title : '表单',
            dataIndex : 'name',
            width: 400,
            key : 'name',
        },
        {
            title : '修改时间',
            dataIndex : 'updateDate',
            key : 'updateDate',
            render : (value:string) => value ?'更新于 '+ moment(value).format('YYYY-MM-DD HH:mm:ss') : '',
        },
        {
            title : '操作',
            key: 'operate',
            width:400,
            render : (value:string) =>(
                <div>
                    <Button color="primary" variant="text">编辑</Button>
                    <Button color="primary" variant="text">导出</Button>
                    <Button color="primary" variant="text">更多</Button>
                </div>
            )

        },
    ]

    // 声明函数
    const getFormGroups = (name: string ) => {
        formApi.getFormGroupList(name).then((res) => {
            const result = res.result;

            if (result.case === 'successData'){
                setFormGroups( result.value.dataList?.group)
            }
            else {
                setNotificationQueue({ type: 'error' , message: `请求失败: ${result.value?.message}`});
            }
        }).catch(() => { })
    }

    // 查询
    const SearchValue = (e: React.ChangeEvent<HTMLInputElement>) =>{
        const value = e.target.value
        setSearchValue(value);
        getFormGroups(value);
    }

    // 显示抽屉
    const onCollapseChange = (keys: string | string[]) => {
        setActiveKeys(Array.isArray(keys) ? keys : [keys]);
    };

    // 动态添加分组
    const collapse_form_groups = formGroups?.map(group =>{

        const group_setting_item :MenuProps['items']=[
            {
                key:`${group.id}-${group.name}-重命名`,
                label:
                    <a onClick={ e => updateGroup(group.id , group.name)}>
                        重命名
                    </a>
            },
            {
                key:`${group.id}-${group.name}-删除该组`,
                label:
                    <Popconfirm
                        title="删除分组"
                        description ={`是否确认删除分组【${group.name}】`}
                        onConfirm={ e => deleteGroup(group.id)}
                        okText="是"
                        cancelText="否"
                    >
                        <a>
                            删除该组
                        </a>
                    </Popconfirm>
            }
        ]

        return {
            key : group.id,
            label :
            <div className='flex-between'>
                <div>
                    {group.name}({group.total})
                </div>
                <div>
                    <Dropdown menu={{items : group_setting_item}} placement="bottom">
                        <Button icon={<BarsOutlined />} color="default" variant="link">分组设置</Button>
                    </Dropdown>
                </div>
            </div>,
            children :
                <Table dataSource={group.child} columns={from_columns}
                       rowKey="id" pagination={false} />
        }
    })

    // 新增分组
    const addFormGroup = () => {
        setGroupForm(base_form_default)
        setGroupModelTitle('新增分组');
        setIsOpen(true);
    }
    // 取消新增分组
    const cancelAddGroup = () =>{
        setIsOpen(false);
        setGroupForm(base_form_default)
        getFormGroups('');
    }

    const groupNameValueChange = (e: React.ChangeEvent<HTMLInputElement>) =>{
        setGroupForm(group => ({ ...group, name : e.target.value }))
    }


    // 新增分组
    const submitFormGroup = () =>{

        if (validator.isEmpty(groupForm.name)){
            return setNotificationQueue({ type: 'warning' , message: `分组名称不能为空`});
        }

        // 新增
        if (validator.isEmpty(groupForm.id)){
            formApi.addFormGroup({name : groupForm.name ,description:''}).then((res) => {
                const result = res.result;
                if (result.case === 'successData'){
                    cancelAddGroup()
                    setNotificationQueue({type: 'success', message: '新增成功'})
                }
                else {
                    setNotificationQueue({ type: 'error' , message: `请求失败: ${result.value?.message}`});
                }

            }).catch((e) => {
                setNotificationQueue({ type: 'error' , message: `请求失败: ${e}`});
            })
        }
        else {
            formApi.updateFormGroup({id:groupForm.id ,name :groupForm.name ,description:''}).then((res) => {
                const result = res.result;
                if (result.case === 'successData'){
                    cancelAddGroup()
                    setNotificationQueue({type: 'success', message: '修改成功'})
                }
                else {
                    setNotificationQueue({ type: 'error' , message: `请求失败: ${result.value?.message}`});
                }

            }).catch((e) => {
                setNotificationQueue({ type: 'error' , message: `请求失败: ${e}`});
            })
        }

    }

    // 修改分组名称
    const updateGroup =(id:string , name:string) => {
        if (validator.isEmpty(id)){
            return setNotificationQueue({ type: 'warning' , message: `请选择一个分组`});
        }

        setGroupForm(create(FormGroupSchema , { name, id }))
        setGroupModelTitle('编辑分组名称');
        setIsOpen(true);
    }

    const deleteGroup = (id:string) =>{
        if (validator.isEmpty(id)){
            return setNotificationQueue({ type: 'warning' , message: `请选择一个分组`});
        }

        formApi.deleteFormGroup({id , name:'' ,description:''}).then((res) => {
            const result = res.result;
            if (result.case === 'successData'){
                cancelAddGroup()
                setNotificationQueue({type: 'success', message: '成功'})
            }
            else {
                setNotificationQueue({ type: 'error' , message: `请求失败: ${result.value?.message}`});
            }

        }).catch((e) => {
            setNotificationQueue({ type: 'error' , message: `请求失败: ${e}`});
        })

    }

    // 挂载
    useEffect(() => {
        getFormGroups('');
    }, []);

    useEffect(() => {
        if (notificationQueue) {
            api[notificationQueue.type]({
                message: notificationQueue.message,
                placement: 'topRight',
                duration: 3,
            });
            setNotificationQueue(null);
        }
    }, [notificationQueue, api]);

    return (
        <Layout className='form-group-component'>
            {contextHolder}
            <Header className='header flex-between flex-warp'>
                <span>表单管理</span>
                <div className='flex-all-center right-model'>
                    <Input addonBefore={<SearchOutlined />} placeholder="搜索表单"
                           value={searchValue} onChange={SearchValue}/>
                    <Button icon={<PlusCircleOutlined />} onClick={addFormGroup}>新建分组</Button>
                    <Button type="primary">创建审批表单</Button>
                </div>
            </Header>
            <Content className='content' style={{
                height: 'calc(100vh - 64px)', // 计算高度，减去 Header 高度
                overflow: 'auto' // 添加滚动条
            }}>
                <ConfigProvider
                    theme={{
                        components: {
                            Collapse: {
                                headerBg:"#fff"
                            }
                        },
                    }}
                >
                    <Collapse items={collapse_form_groups} activeKey={activeKeys}
                              onChange={onCollapseChange} />
                </ConfigProvider>
            </Content>
            <Modal
                title={groupModelTitle}
                open={isOpen}
                onOk={submitFormGroup}
                onCancel={cancelAddGroup}
                okText = '确认'
                cancelText = '取消'
                width='400px'
                wrapClassName = {'add-group-dialog'}
            >
                <Input value={groupForm.id} placeholder="分组名称" style={{display:'none'}}/>
                <Input value={groupForm.name} onChange={groupNameValueChange} placeholder="分组名称"/>
            </Modal>
        </Layout>
    )
}

export default FormGroupComponent